const db = require('../config/database')
const logger = require('../utils/logger')
const pointsService = require('./pointsService')

class RewardService {
  /**
   * 广告观看奖励
   */
  static async rewardAdWatch(userId, adId, adType, adSource, platform, viewDuration, isCompleted, ipAddress, userAgent) {
    try {
      // 检查用户是否存在
      const [userRows] = await db.execute(
        'SELECT id, nickname FROM users WHERE id = ?',
        [userId]
      )
      
      if (userRows.length === 0) {
        throw new Error('用户不存在')
      }

      // 检查今日观看次数
      const today = new Date().toISOString().split('T')[0]
      const [viewRows] = await db.execute(
        'SELECT COUNT(*) as count FROM ad_views WHERE user_id = ? AND DATE(created_at) = ? AND is_completed = 1',
        [userId, today]
      )

      const todayViews = viewRows[0].count
      const maxDailyViews = 10 // 每日最大观看次数

      if (todayViews >= maxDailyViews) {
        throw new Error('今日观看次数已达上限')
      }

      // 记录广告观看
      await db.execute(
        `INSERT INTO ad_views (user_id, ad_id, ad_type, ad_source, platform, view_duration, is_completed, ip_address, user_agent, created_at)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())`,
        [userId, adId, adType, adSource, platform, viewDuration, isCompleted, ipAddress, userAgent]
      )

      let rewardPoints = 0
      if (isCompleted) {
        // 根据广告类型给予不同奖励
        const rewardMap = {
          'video': 5,
          'banner': 1,
          'interstitial': 3,
          'native': 2
        }
        rewardPoints = rewardMap[adType] || 1

        // 发放积分奖励
        await pointsService.addPoints(userId, rewardPoints, 'ad_watch', `观看${adType}广告奖励`)
      }

      return {
        rewardPoints,
        todayViews: todayViews + (isCompleted ? 1 : 0),
        remainingViews: Math.max(0, maxDailyViews - todayViews - (isCompleted ? 1 : 0))
      }
    } catch (error) {
      logger.error('广告观看奖励失败:', error)
      throw error
    }
  }

  /**
   * 邀请好友注册奖励
   */
  static async rewardInviteRegister(inviterId, inviteeId, inviteCode) {
    try {
      // 检查邀请人和被邀请人是否存在
      const [inviterRows] = await db.execute(
        'SELECT id, nickname FROM users WHERE id = ?',
        [inviterId]
      )
      
      const [inviteeRows] = await db.execute(
        'SELECT id, nickname FROM users WHERE id = ?',
        [inviteeId]
      )

      if (inviterRows.length === 0) {
        throw new Error('邀请人不存在')
      }

      if (inviteeRows.length === 0) {
        throw new Error('被邀请人不存在')
      }

      // 检查是否已经被邀请
      const [existingRows] = await db.execute(
        'SELECT id FROM user_invitations WHERE invitee_id = ?',
        [inviteeId]
      )

      if (existingRows.length > 0) {
        throw new Error('该用户已被邀请')
      }

      // 记录邀请关系
      await db.execute(
        `INSERT INTO user_invitations (inviter_id, invitee_id, invite_code, status, created_at)
         VALUES (?, ?, ?, 'completed', NOW())`,
        [inviterId, inviteeId, inviteCode]
      )

      // 给邀请人奖励
      const inviterRewardPoints = 20
      const inviterReward = await pointsService.addPoints(
        inviterId, 
        inviterRewardPoints, 
        'invite_register', 
        `邀请好友${inviteeRows[0].nickname}注册奖励`
      )

      // 给被邀请人奖励
      const inviteeRewardPoints = 10
      const inviteeReward = await pointsService.addPoints(
        inviteeId, 
        inviteeRewardPoints, 
        'register_bonus', 
        '新用户注册奖励'
      )

      return {
        inviterReward,
        inviteeReward
      }
    } catch (error) {
      logger.error('邀请注册奖励失败:', error)
      throw error
    }
  }

  /**
   * 邀请好友消费奖励
   */
  static async rewardInviteConsume(inviteeId, consumeAmount, orderId) {
    try {
      // 查找邀请关系
      const [inviteRows] = await db.execute(
        'SELECT inviter_id FROM user_invitations WHERE invitee_id = ? AND status = "completed"',
        [inviteeId]
      )

      if (inviteRows.length === 0) {
        return null // 无邀请关系
      }

      const inviterId = inviteRows[0].inviter_id

      // 计算奖励积分（消费金额的5%）
      const rewardPoints = Math.floor(consumeAmount * 0.05)

      if (rewardPoints > 0) {
        // 发放奖励给邀请人
        await pointsService.addPoints(
          inviterId, 
          rewardPoints, 
          'invite_consume', 
          `邀请好友消费奖励，订单号：${orderId}`
        )

        // 记录邀请消费奖励
        await db.execute(
          `INSERT INTO invite_consume_rewards (inviter_id, invitee_id, order_id, consume_amount, reward_points, created_at)
           VALUES (?, ?, ?, ?, ?, NOW())`,
          [inviterId, inviteeId, orderId, consumeAmount, rewardPoints]
        )

        return { rewardPoints }
      }

      return null
    } catch (error) {
      logger.error('邀请消费奖励失败:', error)
      throw error
    }
  }

  /**
   * 充值赠送积分
   */
  static async rewardRechargeBonus(userId, rechargeAmount, rechargeId) {
    try {
      // 基础积分（1元=1积分）
      const basePoints = Math.floor(rechargeAmount)
      
      // 计算赠送比例
      let bonusRate = 0
      if (rechargeAmount >= 100) {
        bonusRate = 0.2 // 20%赠送
      } else if (rechargeAmount >= 50) {
        bonusRate = 0.15 // 15%赠送
      } else if (rechargeAmount >= 20) {
        bonusRate = 0.1 // 10%赠送
      }

      const bonusPoints = Math.floor(basePoints * bonusRate)
      const totalPoints = basePoints + bonusPoints

      // 发放基础积分
      await pointsService.addPoints(
        userId, 
        basePoints, 
        'recharge', 
        `充值${rechargeAmount}元获得积分`
      )

      // 发放赠送积分
      if (bonusPoints > 0) {
        await pointsService.addPoints(
          userId, 
          bonusPoints, 
          'recharge_bonus', 
          `充值${rechargeAmount}元赠送积分`
        )
      }

      return {
        basePoints,
        bonusPoints,
        totalPoints,
        bonusRate
      }
    } catch (error) {
      logger.error('充值赠送积分失败:', error)
      throw error
    }
  }

  /**
   * 活动奖励积分
   */
  static async rewardActivity(userId, points, activityName, activityId, expireTime) {
    try {
      // 检查是否已经参与过该活动
      const [existingRows] = await db.execute(
        'SELECT id FROM activity_rewards WHERE user_id = ? AND activity_id = ?',
        [userId, activityId]
      )

      if (existingRows.length > 0) {
        throw new Error('已经参与过该活动')
      }

      // 发放活动奖励积分
      await pointsService.addPoints(
        userId, 
        points, 
        'activity', 
        `参与活动"${activityName}"奖励`,
        expireTime
      )

      // 记录活动参与
      await db.execute(
        `INSERT INTO activity_rewards (user_id, activity_id, activity_name, reward_points, expire_time, created_at)
         VALUES (?, ?, ?, ?, ?, NOW())`,
        [userId, activityId, activityName, points, expireTime]
      )

      return {
        points,
        activityName,
        expireTime
      }
    } catch (error) {
      logger.error('活动奖励积分失败:', error)
      throw error
    }
  }

  /**
   * 获取今日广告观看情况
   */
  static async getTodayAdViews(userId) {
    try {
      const today = new Date().toISOString().split('T')[0]
      
      const [viewRows] = await db.execute(
        `SELECT 
           COUNT(*) as total_views,
           SUM(CASE WHEN is_completed = 1 THEN 1 ELSE 0 END) as completed_views,
           SUM(CASE WHEN is_completed = 1 THEN 
             CASE ad_type 
               WHEN 'video' THEN 5
               WHEN 'interstitial' THEN 3
               WHEN 'native' THEN 2
               WHEN 'banner' THEN 1
               ELSE 1
             END
           ELSE 0 END) as earned_points
         FROM ad_views 
         WHERE user_id = ? AND DATE(created_at) = ?`,
        [userId, today]
      )

      const maxDailyViews = 10
      const completedViews = viewRows[0].completed_views || 0
      const remainingViews = Math.max(0, maxDailyViews - completedViews)

      return {
        totalViews: viewRows[0].total_views || 0,
        completedViews,
        earnedPoints: viewRows[0].earned_points || 0,
        remainingViews,
        maxDailyViews
      }
    } catch (error) {
      logger.error('获取今日广告观看情况失败:', error)
      throw error
    }
  }

  /**
   * 获取邀请统计
   */
  static async getInviteStatistics(userId) {
    try {
      // 邀请人数统计
      const [inviteCountRows] = await db.execute(
        'SELECT COUNT(*) as invite_count FROM user_invitations WHERE inviter_id = ? AND status = "completed"',
        [userId]
      )

      // 邀请奖励统计
      const [inviteRewardRows] = await db.execute(
        `SELECT 
           COALESCE(SUM(CASE WHEN type = 'invite_register' THEN points ELSE 0 END), 0) as register_rewards,
           COALESCE(SUM(CASE WHEN type = 'invite_consume' THEN points ELSE 0 END), 0) as consume_rewards
         FROM points_transactions 
         WHERE user_id = ? AND type IN ('invite_register', 'invite_consume')`,
        [userId]
      )

      // 本月邀请统计
      const currentMonth = new Date().toISOString().slice(0, 7)
      const [monthlyRows] = await db.execute(
        'SELECT COUNT(*) as monthly_invites FROM user_invitations WHERE inviter_id = ? AND DATE_FORMAT(created_at, "%Y-%m") = ?',
        [userId, currentMonth]
      )

      return {
        totalInvites: inviteCountRows[0].invite_count || 0,
        monthlyInvites: monthlyRows[0].monthly_invites || 0,
        registerRewards: inviteRewardRows[0].register_rewards || 0,
        consumeRewards: inviteRewardRows[0].consume_rewards || 0,
        totalRewards: (inviteRewardRows[0].register_rewards || 0) + (inviteRewardRows[0].consume_rewards || 0)
      }
    } catch (error) {
      logger.error('获取邀请统计失败:', error)
      throw error
    }
  }
}

module.exports = RewardService